package com.jdew.thkj.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.adapter.PddLeiMuAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.pddBean;
import com.jdew.thkj.listener.AppBarStateChangeListener;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.view.Reflex;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/8.
 */

public class PddActivity extends BaseActivity {
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.search)
    TextView search;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    @Bind(R.id.iv_1)
    ImageView iv1;
    @Bind(R.id.iv_2)
    ImageView iv2;
    @Bind(R.id.iv_3)
    ImageView iv3;
    @Bind(R.id.iv_4)
    ImageView iv4;
    @Bind(R.id.iv_5)
    ImageView iv5;
    @Bind(R.id.iv_6)
    ImageView iv6;
    @Bind(R.id.iv_7)
    ImageView iv7;
    @Bind(R.id.iv_8)
    ImageView iv8;
    @Bind(R.id.iv_9)
    ImageView iv9;
    @Bind(R.id.iv_10)
    ImageView iv10;
    private String[] mTilte;
    private PddLeiMuAdapter adapter;
    private List<pddBean.DataBean> list = new ArrayList<>();
    private int page = 1;
    private boolean isLoading = true;
    private String itemid;
    private String key = "0";
    private Dialog mWeiboDialog;

    @Override
    public int bindLayout() {
        return R.layout.activity_pdd;
    }

    @Override
    public void initView(View view) {
        title.setText("拼多多");
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        search.setOnClickListener(this);
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        iv4.setOnClickListener(this);
        iv5.setOnClickListener(this);
        iv6.setOnClickListener(this);
        iv7.setOnClickListener(this);
        iv8.setOnClickListener(this);
        iv9.setOnClickListener(this);
        iv10.setOnClickListener(this);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        xiding();
        mTilte = getResources().getStringArray(R.array.tab_pdd_Title);
        adapter = new PddLeiMuAdapter(this, list);
        setRcycleview(recycleView, adapter);
        initRefresh();
        RequestData();
        setRecycleView();
        adapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(PddActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    itemid = list.get(position).getGoods_id();
                    toDetail();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.search: {
                Bundle b = new Bundle();
                b.putSerializable("source", "pdd");
                startActivity(MainSearchActivity.class, b);
            }
            break;
            case R.id.iv_1:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "家居日用");
                startActivity(intent);
            }
            break;
            case R.id.iv_2:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "食品饮料");
                startActivity(intent);
            }
            break;
            case R.id.iv_3:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "母婴");
                startActivity(intent);
            }
            break;
            case R.id.iv_4:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "家用电器");
                startActivity(intent);
            }
            break;
            case R.id.iv_5:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "手机");
                startActivity(intent);
            }
            break;
            case R.id.iv_6:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "数码");
                startActivity(intent);
            }
            break;
            case R.id.iv_7:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "电脑");
                startActivity(intent);
            }
            break;
            case R.id.iv_8:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "服饰内衣");
                startActivity(intent);
            }
            break;
            case R.id.iv_9:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "美妆护肤");
                startActivity(intent);
            }
            break;
            case R.id.iv_10:{
                Intent  intent = new Intent(this, PddSearchActivity.class);
                intent.putExtra("result", "鞋靴");
                startActivity(intent);
            }
            break;
            default:
                break;
        }
    }


    public void toDetail() {
        Bundle b = new Bundle();
        b.putSerializable("itemId", itemid);
        startActivity(PddDetailActivity.class, b);
    }

    public void xiding() {
        appbar.addOnOffsetChangedListener(new AppBarStateChangeListener() {

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    //展开状态
                    swipeRefreshLayout.setEnabled(true);
                } else if (state == State.COLLAPSED) {
                    //折叠状态
                    swipeRefreshLayout.setEnabled(false);
                } else {//中间状态
                    swipeRefreshLayout.setEnabled(false);

                }
            }
        });
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查");
            }
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetCategory(key, page, "0", RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "opt_id" + key + "PageIndex" + page + "sort_type0")).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<pddBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(pddBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.isSuccess()) {
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    isLoading = false;
                    adapter.changeMoreStatus(adapter.LOADING_MORE);
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    private void initRefresh() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                RequestData();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void setRecycleView() {
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = null;
                if (layoutManager instanceof LinearLayoutManager) {
                    linearManager = (LinearLayoutManager) layoutManager;
                }
                int lastVisibleItemPosition = linearManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    boolean isRefreshing = swipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        page++;
                        RequestData();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= 21) {
            Window window = this.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.color_ffffff));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//设置状态栏黑色字体
        }
    }
}
